<template>
  <div class="kepuchuangzuo">
    <div class="articletop">
      <div class="topshuomain">健康科普创作（图文）</div>
    </div>




    <div class="wechat-editor">

      <div class="editor-wrapper">
        <!-- 工具栏 -->
        <!-- <Toolbar :mode="mode" class="editor-toolbar" :editor="editor" :defaultConfig="toolbarConfig" /> -->

        <!-- 编辑区域 -->
        <div class="editor-content">
          <input v-model="title" maxlength="50" placeholder="请在这里输入标题（2~50个字）" class="editor-title"
            @focus="handleTitleFocus" @blur="handleTitleBlur">
          <div>
            <!--   <Editor class="editor-body" :defaultConfig="editorConfig" v-model="html" @onChange="onChange"
              @onCreated="onCreated" @onFocus="handleEditorFocus" /> -->

            <!-- <vue-ueditor-wrap v-model="html" :editor-id="editorId" ref="ueditor" :config="editorConfigV"
              :editorDependencies="['ueditor.config.js', 'ueditor.all.js']" @ready="onEditorReady" /> -->

            <vue-ueditor-wrap v-model="html" :editor-id="editorId" ref="ueditor" :config="editorConfigV"
              :editorDependencies="['ueditor.config.js', 'ueditor.all.js', 'xiumi-ue-dialog-v5.js', 'xiumi-ue-v5.css']"
              :editor-dependencies="['ueditor.config.js', 'ueditor.all.js', 'xiumi-ue-dialog-v5.js', 'xiumi-ue-v5.css']"
              @ready="onEditorReady" style="width: 100%; height: 100%;" />
          </div>
        </div>
        <div style="width: 98%;margin: 0 auto;margin-top: 10px;height: 1px;background-color: #E5E5E5;"></div>
        <div class="form" style="width: 98%;margin: 0 auto;margin-top: 20px;">
          <el-form ref="form" :model="form" :rules="rules" label-width="90px">
            <el-row>

              <el-col :span="24">
                <el-form-item label="内容分类" prop="neilei">
                  <el-select style="width: 100%;" v-model="form.neilei" placeholder="请选择内容分类">
                    <el-option v-for="dict in fenlei" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="关键词" prop="dynamicTags">
                  <el-tag :key="tag" v-for="tag in form.dynamicTags" closable :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{ tag }}
                  </el-tag>
                  <el-input :style="{ marginLeft: form.dynamicTags.length > 0 ? '20px' : '0' }" class="input-new-tag"
                    v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" show-word-limit
                    maxlength="8" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                  </el-input>
                  <el-button :style="{ marginLeft: form.dynamicTags.length > 0 ? '20px' : '0' }" v-else
                    class="button-new-tag" size="small" @click="showInput">+ 添加关键词</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="摘要" prop="zhaiyao">
                  <el-input type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 8, maxRows: 10 }"
                    placeholder="请输入摘要" v-model="form.zhaiyao">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="封面" prop="imgurl">
                  <div class="fenall">

                    <div class="fengmian">
                      <div class="fengmianl" v-if="!form.imgurl">
                        <input type="file" id="uploads" style="position: absolute; opacity: 0; z-index: 9;top: 0; width: 160px;
      height: 90px; " accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImgg($event)" />
                        <div class="zhongxin">
                          <div class="addicon"><img src="../../../assets/images/addtu.png" alt=""></div>
                          <div class="addshuo">上传封面</div>
                        </div>
                      </div>
                      <div class="fengmianl" v-if="form.imgurl">
                        <div class="overchuan">
                          <img :src="form.imgurl" alt="">
                        </div>
                        <div class="chongchuan">
                          <div class="gengicon">
                            <img src="../../../assets/images/genghuan.png" alt="">
                          </div>
                          <div class="gengicontit">更换封面</div>
                        </div>
                        <input type="file" id="uploads" style="position: absolute; opacity: 0; z-index: 9;top: 0; width: 160px;
      height: 90px; " accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImgg($event)" />
                      </div>
                      <div class="fengmianr">支持格式：.jpg、.png、.jpeg等，文件大小不能超过10M</div>
                    </div>

                  </div>

                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="渠道" prop="qudao">
                  <el-checkbox-group @change="changequdao" v-model="form.qudao">
                    <el-checkbox v-for="(item, index) in qudaolist" :key="index" :label="item.dictValue">{{
            item.dictLabel }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="医普号" prop="yipu" v-if="form.qudao.includes('2') && jiaosetype == 3">
                  <el-select filterable style="width: 100%;" v-model="form.yipu" placeholder="请选择医普号">
                    <el-option v-for=" dict  in  yipulist " :key="dict.userId" :label="dict.userName"
                      :value="dict.userId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="阅读量" v-if="jiaosetype == 3" prop=" yudunum">
                  <el-input v-model="form.yudunum" type="number" placeholder="请输入阅读量"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="bottomedit">
        <div class="bottomeditmain">
          <div class="bottomeditmainl">正文字数 {{ wordCount }}</div>
          <div class="bottomeditmainr">
            <div class="subcun" @click="previewClick()">预览</div>
            <div class="subcaogao" @click="submitcaogao()">保存草稿</div>
            <div class="subcun" @click="submitfabu()">发布</div>

          </div>

        </div>
      </div>
    </div>
    <el-dialog top="10vh" title="裁剪封面" :visible.sync="caijianbanner" width="600px" style="">
      <div class="caijian">
        <div class="caijianl">
          <vue-cropper ref="cropperr" :img="optionss.img" :info="true" :autoCrop="optionss.autoCrop"
            :autoCropWidth="optionss.autoCropWidth" :autoCropHeight="optionss.autoCropHeight"
            :fixedBox="optionss.fixedBox" :outputType="optionss.outputType" :canScale="true" @realTime="realTimee" />
        </div>
      </div>
      <div style="display: flex; align-items: center; justify-content: space-between;padding: 15px 0;">
        <div class="anniulist">
          <el-button icon="el-icon-plus" @click="changeScalee(1)">放大</el-button>
          <el-button icon="el-icon-minus" @click="changeScalee(-1)">缩小</el-button>
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()">左旋</el-button>
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()">右旋</el-button>
        </div>

        <div style="margin-top: 10px;" v-if="!caijianFooterButtonShow">
          <el-button type="primary" @click="confimrlogoo()">确定</el-button>
          <el-button @click="cancelfugaii()"> 取消</el-button>
        </div>
      </div>


      <div slot="footer" v-if="caijianFooterButtonShow" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="confimrlogoo()">确定</el-button>
        <el-button @click="cancelfugaii()"> 取消</el-button>

      </div>
    </el-dialog>

    <el-dialog top="10vh" title="预览效果" :visible.sync="previewShow" style="">
      <div class="dialog-preview" v-html="previewHtml">

      </div>
    </el-dialog>

  </div>
</template>

<script>
// import {
//   Editor,
//   Toolbar
// } from "@wangeditor/editor-for-vue";
import {
  VueCropper
} from "vue-cropper";
import {
  addtupian,
  zidian,
  addwenzhang,
  addcaogao,
  yipulistapi,
  detailkepu,
  isjiaose,
  titleUniqueCheck
} from "@/api/system/kepu";
import {
  Notification,
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import VueUeditorWrap from 'vue-ueditor-wrap'
import {
  t
} from "@wangeditor/editor";

let downloadLoadingInstance;
export default {
  name: "createkepu",
  components: {
    // Editor,
    // Toolbar,
    VueUeditorWrap
  },
  data() {
    return {
      title: '',
      // editor: null,
      mode: "default",
      editorId: "editor",
      isTitleFocused: false,
      editorInstance: null, // 保存 UE 实例
      html: "",
      toolbarConfig: {
        excludeKeys: [
          'fullScreen', 'uploadVideo', 'group-video',
          'emotion', 'code', 'todo', 'codeBlock', 'insertImage'
        ],
      },
      editorConfig: {
        placeholder: "从这里开始写正文",
        MENU_CONF: {
          // 图片上传
          uploadImage: {
            // server: `${process.env.VUE_APP_BASE_API}business/jkkepu/commonFileUpload`,
            server: `https://qywx.precare.cn/prod-api/business/jkkepu/commonFileUpload`,
            fieldName: 'file',
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 100 * 1024 * 1024, // 10M
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 100,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
            meta: {
              // token: 'xxx',
              // otherKey: 'yyy'
              // file:''
            },
            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            headers: {
              // Accept: 'text/x-json',
              // otherKey: 'xxx'
            },

            // 跨域是否传递 cookie ，默认为 false
            withCredentials: true,

            // 超时时间，默认为 10 秒
            timeout: 50 * 1000, //10 秒

            // 上传前
            onBeforeUpload(files) {
              downloadLoadingInstance = Loading.service({
                text: "正在上传中，请稍候",
                spinner: "el-icon-loading"
              })
              return files;
            },
            // 自定义插入图片
            customInsert(res, insertFn) {
              // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
              // 先关闭等待的Message
              downloadLoadingInstance.close();
              Message.closeAll();
              if (res.code === 200) {
                downloadLoadingInstance.close();
                Message.success({
                  message: `上传成功`
                });
              } else {
                downloadLoadingInstance.close();
                Message.error({
                  message: res.msg
                });
              }
              insertFn(res.data.url, res.data.name, res.data.url);
            },

            // 单个文件上传成功之后
            onSuccess(file, res) {

              // Message.success({
              //   message: `上传成功`
              // });;
            },

            // 单个文件上传失败
            onFailed(file, res) {
              downloadLoadingInstance.close();
              // Notification.error({
              //   title: '错误',
              //   message: `上传失败，请重新尝试`
              // });
            },

            // 上传进度的回调函数
            onProgress(progress) {

              console.log('progress', progress);

              // progress 是 0-100 的数字
            },

            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {

              Message.error("上传失败，请检查格式或大小，大小不超过5M");
              downloadLoadingInstance.close();
            }
          },
        },
      },

      previewShow: false,
      previewHtml: '',
      editorConfigV: {
        // 后端服务地址，后端处理参考
        // https://open-doc.modstart.com/ueditor-plus/backend.html
        //  serverUrl: '/api/path/to/server',
        serverUrl: `${process.env.VUE_APP_BASE_API}business/jkkepu/editorFileUpload`,
        // initialContent: '<p>初始化内容</p>',

        // serverUrl: `https://qywx.precare.cn/prod-api/business/jkkepu/commonFileUpload`,

        // UEDITOR_HOME_URL: '/static/UEditorPlus/',
        // UEDITOR_CORS_URL: '/static/UEditorPlus/',
        UEDITOR_HOME_URL: '/UEditor/',
        UEDITOR_CORS_URL: '/UEditor/',
        // loadConfigFromServer: false, // 是否从服务端加载配置
        autoHeightEnabled: false, // 自动高度
        autoSaveEnable: true, // 自动保存
        // saveInterval: 2000,
        // autoSaveRestore: true, // 自动保存，自动恢复
        initialFrameHeight: 650, // 编辑器高度
        initialFrameWidth: '100%', // 设置宽度
        // 允许上传的文件类型
        allowFileTypes: ['image', 'media', 'file'],
        // 图片上传配置
        imageActionName: 'uploadimage', // 执行上传图片的action名称
        imageFieldName: 'file', // 提交的图片表单名称
        imageMaxSize: 10485760, // 上传大小限制，单位B
        maximumWords: 50000,
        imageUrlPrefix: '', // 确保这是图片访问的正确前缀
        imageAllowFiles: ['.png', '.jpg', '.jpeg', '.gif', '.bmp'], // 上传图片格式显示
        catchRemoteImageEnable: false, // 是否抓取远程图片
        uploadServiceEnable: false, // 启用上传服务
        uploadServiceUpload: function (type, file, callback, option) {
          console.log('uploadServiceUpload', type, file, callback, option);
          let formData = new FormData();
          formData.append("file", file);
          addtupian(formData).then(res => {
            if (res.code == 200) {
              // this.form.imgurl = res.data.url
              // this.caijianbanner = false;
              callback.success({
                "state": "SUCCESS",
                "url": res.data.url,
              })
              return;
              // downloadLoadingInstance.close();
            } else {
              // downloadLoadingInstance.close();
            }
          });

        },
        toolbars: [
          [
            'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript',
            'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor',
            'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase',
            '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'insertframe',
            'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol',
            'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols',
            'charts', '|',
            'print', 'preview', 'searchreplace', 'drafts', 'help'
          ]
        ]
      },
      form: {
        qudao: [],
        dynamicTags: [],
        imgurl: '',
        articleId: ''

      },
      fenlei: [

      ],
      rules: {

        zhaiyao: [{
          required: true,
          message: "摘要不能为空",
          trigger: "blur"
        }],
        imgurl: [{
          required: true,
          message: "封面不能为空",
          trigger: "blur"
        }],
        neilei: [

          {
            required: true,
            message: "内容分类不能为空",
            trigger: "change"
          }

        ],
        dynamicTags: [

          {
            required: true,
            message: "关键词不能为空",
            trigger: "blur"
          }

        ],
        qudao: [

          {
            required: true,
            message: "渠道不能为空",
            trigger: "change"
          }

        ],

      },
      inputVisible: false,
      inputValue: '',
      wordCount: 0, // 正文字数
      optionss: {
        img: "", //裁剪图片的地址
        name: "封面",
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 480, // 默认生成截图框宽度
        autoCropHeight: 270, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        outputType: "png" // 默认生成截图为PNG格式
      },
      caijianbanner: false,
      previewss: {},
      qudaolist: [],
      yipulist: [],
      jiaosetype: "",
      caijianFooterButtonShow: true,
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,

    };
  },
  created() {
    this.html = ""
    this.getzidian()
    this.getqudao()
    this.getyipudata()
    let id = this.$route.query.id;
    if (id) {
      this.form.articleId = id
      this.getdetail()
      this.editorId = "editor-cao-gao";
    }
    this.getjiaose()

  },

  mounted() {
    // this.$nextTick(() => {

    //   console.log("this.$refs.ueditor",this.$refs.ueditor)
    //   const editor = this.$refs.ueditor.getEditor();
    //   editor.addListener('contentChange', () => {
    //     console.log('内容变化了', editor.getContent());
    //   });
    // });

    this.getFooterButtonShow()

    window.addEventListener('resize', this.handleResize);
  },

  methods: {

    getFooterButtonShow() {
      // const width = window.innerWidth;
      // const height = window.innerHeight;

      if (this.windowHeight < 603) {
        this.caijianFooterButtonShow = false;
      }
    },

    handleResize() {
      this.windowWidth = window.innerWidth;
      this.windowHeight = window.innerHeight;
      console.log('窗口大小变化:', this.windowWidth, this.windowHeight);

      if (this.windowHeight < 603) {
        this.caijianFooterButtonShow = false;
      } else {
        this.caijianFooterButtonShow = true;
      }
    },

    onEditorReady(editor) {
      this.editorInstance = editor;
      console.log('UEditor 准备好了');

      if (this.editorId != "editor-cao-gao") {
        let draft = editor.execCommand('get_auto_save_content');
        if (draft) {
          setTimeout(() => {
            editor.execCommand('auto_save_restore');
            this.$message({
              message: "已从草稿恢复",
              type: "success"
            });
          }, 500);
        }
      }



      // 示例：监听内容变化
      this.editorInstance.addListener('contentChange', () => {
        // console.log('内容变了：', this.editorInstance.getContent());
        // 基础版本：统计所有字符（包含空格）
        this.wordCount = this.editorInstance.getContentTxt().trim().length;
      });

      // 注册销毁钩子（只执行一次）
      // this.$once('hook:beforeDestroy', () => {
      //   try {
      //     if (this.editorInstance && this.editorInstance.destroy) {
      //       // 防止 parentNode 读取异常
      //       if (this.editorInstance.container && this.editorInstance.container.parentNode) {
      //         this.editorInstance.destroy();
      //         console.log('UEditor 安全销毁');
      //       } else {
      //         console.warn('UEditor container 不存在，跳过 destroy');
      //       }
      //     }
      //     this.editorInstance = null;
      //   } catch (e) {
      //     console.error('销毁编辑器异常：', e);
      //   }
      // });

    },

    previewClick() {
      this.previewHtml = this.html;
      this.previewShow = true;
    },
    getjiaose() {
      isjiaose({

      }).then(res => {
        this.jiaosetype = res.data.roleId
      })
    },
    reset() {
      this.form = {
        // articleId: null,
        neilei: null,
        dynamicTags: null,
        zhaiyao: null,
        imgurl: null,
        qudao: [],
        yipu: null,
        yudunum: null,
      };
      this.resetForm("form");
    },
    getdetail() {
      detailkepu({
        articleId: this.form.articleId
      }).then(res => {
        this.reset()
        this.title = res.data.title
        this.html = res.data.content
        this.form.neilei = res.data.contentType
        if (res.data.keyWord) {
          this.form.dynamicTags = res.data.keyWord.split(',')

        } else {
          this.form.dynamicTags = []
        }
        this.form.zhaiyao = res.data.abstracts
        this.form.imgurl = res.data.coverUrl
        if (res.data.channel) {
          this.form.qudao = res.data.channel.split(',')

        } else {
          this.form.qudao = []
        }
        this.form.yipu = res.data.authorUserId
        this.form.yudunum = res.data.readingNum
        this.form.articleId = res.data.articleId
      })
    },
    getzidian() {
      zidian({
        dictType: "article_content_type"
      }).then(res => {
        this.fenlei = res.data
      })
    },
    getqudao() {
      zidian({
        dictType: "article_channel"
      }).then(res => {
        this.qudaolist = res.data
      })
    },
    getyipudata() {
      yipulistapi({}).then(res => {
        this.yipulist = res.data
      })
    },
    changequdao() {
      console.log(this.form.qudao)

      if (this.form.qudao.length == 0) {
        this.form.yipu = null
      }

    },
    submitcaogao() {

      let guanjiaci = this.form.dynamicTags.join(',')
      let qudao = this.form.qudao.join(',')
      let authorUserId = ""
      let authorUserName = ""
      let msg = ""
      if (this.form.qudao.includes('2')) {
        // if (!this.form.yipu) {
        //   msg = "请选择医普号"
        //   this.$message({
        //     message: "请选择医普号",
        //     type: "error"
        //   });
        // } else {
        authorUserId = this.form.yipu
        for (let i = 0; i < this.yipulist.length; i++) {
          if (this.yipulist[i].userId === authorUserId) {
            authorUserName = this.yipulist[i].userName
            break;
          }
        }
        // }

      } else {
        authorUserId = ""
        authorUserName = ""
      }
      if (!this.title) {
        msg = "请输入标题"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      } else {
        const trimmedTitle = this.title.trim();
        if (!trimmedTitle) {
          this.$message.error("标题不能为空或全为空格");
          return;
        }
        if (trimmedTitle.length < 2) {
          this.$message.error("标题不能少于 2 个字");
          return;
        }
        if (trimmedTitle.length > 50) {
          this.$message.error("标题不能超过 50 个字");
          return;
        }
      }
      if (!this.form.imgurl) {
        msg = "请上传封面"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }
      if (msg == "") {
        addcaogao({
          title: this.title,
          abstracts: this.form.zhaiyao,
          keyWord: guanjiaci,
          contentType: this.form.neilei,
          coverUrl: this.form.imgurl,
          content: this.html,
          articleType: "1",
          channel: qudao,
          authorUserId: authorUserId,
          authorUserName: authorUserName,
          readingNum: this.form.yudunum,
          articleId: this.form.articleId
        }).then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.$router.go(-1);
        })
      }

    },
    submitfabu() {
      let guanjiaci = this.form.dynamicTags.join(',')
      let qudao = this.form.qudao.join(',')
      let authorUserId = ""
      let authorUserName = ""
      let msg = ""

      // Validate in order
      if (!this.title) {
        msg = "请输入标题"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      } else {
        const trimmedTitle = this.title.trim();
        if (!trimmedTitle) {
          this.$message.error("标题不能为空或全为空格");
          return;
        }
        if (trimmedTitle.length < 2) {
          this.$message.error("标题不能少于 2 个字");
          return;
        }
        if (trimmedTitle.length > 50) {
          this.$message.error("标题不能超过 50 个字");
          return;
        }
      }
      if (!this.html || this.html === '<p><br></p>') {
        msg = "请输入内容"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }

      if (!this.form.neilei) {
        msg = "请选择内容分类"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }

      if (this.form.dynamicTags.length == 0) {
        msg = "请添加关键词"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }

      if (!this.form.zhaiyao) {
        msg = "请输入摘要"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }

      if (!this.form.imgurl) {
        msg = "请上传封面"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }
      if (this.form.qudao.length == 0) {
        msg = "请选择渠道"
        this.$message({
          message: msg,
          type: "error"
        });
        return
      }

      if (this.form.qudao.includes('2') && this.jiaosetype == '3') {
        if (!this.form.yipu) {
          msg = "请选择医普号"
          this.$message({
            message: msg,
            type: "error"
          });
          return
        } else {
          authorUserId = this.form.yipu
          for (let i = 0; i < this.yipulist.length; i++) {
            if (this.yipulist[i].userId === authorUserId) {
              authorUserName = this.yipulist[i].userName
              break
            }
          }
        }
      } else {
        authorUserId = ""
        authorUserName = ""
      }

      // If all validations pass
      addwenzhang({
        title: this.title,
        abstracts: this.form.zhaiyao,
        keyWord: guanjiaci,
        contentType: this.form.neilei,
        coverUrl: this.form.imgurl,
        content: this.html,
        articleType: "1",
        channel: qudao,
        authorUserId: authorUserId,
        authorUserName: authorUserName,
        readingNum: this.form.yudunum,
        articleId: this.form.articleId
      }).then(res => {
        console.log("邹部长", res)
        if (res.code == 4001) {
          this.$message({
            message: res.msg,
            type: "error"
          });
          this.$nextTick(() => {
            this.html = res.data;

            // 强制重新渲染编辑器内容
            if (this.editor) {
              this.editor.setHtml(res.data);
            }
          });
          // this.html = res.data
        }
        if (res.code == 200) {
          this.$message({
            message: "提交成功",
            type: "success"
          });
          this.$router.go(-1);
        }

      })
    },
    cancelfugaii() {
      this.caijianbanner = false;
      this.optionss.img = "";
      // 重置所有文件输入
      const inputs = document.querySelectorAll('#uploads');
      inputs.forEach(input => input.value = '');
    },
    shangchuan() {
      // this.form.imgurl = "https://www.wangeditor.com/image/elem-type.png"
      this.$refs.cropperr.getCropBlob(data => {
        let formData = new FormData();
        formData.append("file", data);
        // let imgId = this.hosinfo.imgbannerid;
        // if (imgId) {
        //   formData.append("imgId", imgId);
        // }
        let downloadLoadingInstance = Loading.service({
          text: "正在上传中，请稍候",
          spinner: "el-icon-loading"
        })
        addtupian(formData).then(res => {
          if (res.code == 200) {
            this.form.imgurl = res.data.url
            this.caijianbanner = false;
            downloadLoadingInstance.close();
          } else {
            downloadLoadingInstance.close();
          }
        });
      });
    },
    confimrlogoo() {
      this.shangchuan();
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropperr.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropperr.rotateRight();
    },
    changeScalee(num) {
      num = num || 1;
      this.$refs.cropperr.changeScale(num);
    },
    realTimee(data) {
      this.previewss = data;
    },

    selectImgg(e) {
      this.optionss.img = "";
      let file = e.target.files[0];

      // 重置input的值，允许重复选择同一文件
      e.target.value = '';

      if (!file) return;

      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(file.name)) {
        this.$message({
          message: "图片类型要求：jpeg、jpg、png",
          type: "error"
        });
        return false;
      }

      const maxSize = 10 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$message.error('文件大小超过5MB限制，请选择更小的图片');
        return;
      }

      let reader = new FileReader();
      reader.onload = e => {
        this.optionss.img = e.target.result;
        this.caijianbanner = true;
      };

      reader.onerror = () => {
        this.$message.error('文件读取失败，请重试');
      };

      reader.readAsDataURL(file);
      this.optionss.name = "封面";
    },
    updateWordCount() {
      if (this.editor) {
        const text = this.editor.getText().trim();
        // 基础版本：统计所有字符（包含空格）
        this.wordCount = text.length;

        // 高级版本：统计汉字和字符（中文算1，英文单词算1）
        // const chinese = text.match(/[\u4e00-\u9fa5]/g) || [];
        // const english = text.match(/\b[a-zA-Z]+\b/g) || [];
        // this.wordCount = chinese.length + english.length;
      }
    },
    handleClose(tag) {
      this.form.dynamicTags.splice(this.form.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        // 正确调用Element Input组件的focus方法
        this.$refs.saveTagInput.focus();
      });
    },

    handleInputConfirm() {

      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.dynamicTags.push(inputValue);
      } else {
        // this.$message({
        //   message: "关键词不能为空",
        //   type: "error"
        // });
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
      this.updateWordCount(); // 添加初始化统计
    },
    onChange(editor) {
      console.log("内容变化:", editor.getHtml());
      this.updateWordCount(); // 添加此行
    },
    handleTitleFocus() {
      this.isTitleFocused = true;
    },
    handleTitleBlur() {
      this.isTitleFocused = false;
      console.log("标题失去焦点", this.title);
      if (!this.title) return;
      titleUniqueCheck({
        title: this.title,
        articleId: this.form.articleId
      }).then(res => {
        if (res.code == 200) {
          // this.$message({
          //   message: "标题可用",
          //   type: "success"
          // });
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      })
    },
    handleEditorFocus() {
      this.isTitleFocused = false;
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    // if (this.editor) this.editor.destroy();
  }
};
</script>
<style>
.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  width: 120px;

  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  /* margin-left: 10px; */

}

.input-new-tag {
  width: 120px;
  vertical-align: bottom;
  /* margin-left: 10px; */
}
</style>
<style>
input:focus {
  outline: none;
}

.bg-my-color {
  background-color: #fff;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.anniulist {
  display: flex;
  margin-top: 10px;
}

.dialog-preview {
  // width: 800px;

  ::v-deep img {
    width: 100% !important;
  }
}

.preview {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

::v-deep .el-dialog__body {
  padding-top: 10px !important;
  padding-bottom: 5px !important;
}

.caijian {
  display: flex;
  justify-content: space-between;

  .caijianl {
    width: 600px;
    height: 400px;
  }

  .caijianr {

    .tutit {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      line-height: 40px;
    }
  }
}

.fenall {
  .fengmian {
    display: flex;
    width: 100%;

    .fengmianr {
      line-height: 90px;
      margin-left: 20px;
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 12px;
      color: #C1C1C1;
    }

    .fengmianl {
      width: 160px;
      height: 90px;
      background: #F2F3F3;
      border-radius: 4px 4px 4px 4px;

      .zhongxin {
        width: 52px;
        height: 50px;
        margin: 0 auto;
        margin-top: 25px;
        text-align: center;

        .addicon {
          width: 25px;
          height: 25px;
          margin: 0 auto;

          img {
            width: 25px;
            height: 25px;
          }
        }

        .addshuo {
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 13px;
          color: #999999;
          line-height: 25px;
          text-align: center;
        }
      }

      .chongchuan {
        width: 52px;
        height: 50px;
        margin: 0 auto;
        margin-top: 25px;
        text-align: center;

        .gengicon {
          width: 25px;
          height: 25px;
          margin: 0 auto;

          img {
            width: 25px;
            height: 25px;
          }
        }

        .gengicontit {
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 13px;
          color: #fff;
          line-height: 25px;
          text-align: center;
        }
      }
    }

    .fengmianl {
      position: relative;
      width: 160px;
      height: 90px;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;

      &:hover {
        .overchuan::after {
          opacity: 1;
        }

        .chongchuan {
          opacity: 1;
          transform: translate(-50%, -50%) scale(1);
        }
      }

      .overchuan {
        position: relative;
        width: 100%;
        height: 100%;

        img {
          width: 160px;
          height: 90px;
        }

        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.5);
          opacity: 0;
          transition: opacity 0.3s;
        }
      }

      .chongchuan {
        position: absolute;
        top: 25%;
        left: 50%;
        transform: translate(-50%, -50%) scale(0.8);
        opacity: 0;
        transition: all 0.3s ease;
        z-index: 2;
        text-align: center;

        .gengicon {
          width: 25px;
          height: 25px;
          margin: 0 auto;

          img {
            width: 100%;
            height: 100%;
            filter: brightness(0) invert(1); // 图标变白色
          }
        }

        .gengicontit {
          color: white;
          font-size: 12px;
          line-height: 25px;
        }
      }

      input[type="file"] {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
        z-index: 3;
      }
    }
  }
}


.kepuchuangzuo {
  width: 100%;

  .articletop {
    width: 95%;
    height: 60px;
    margin: 0 auto;
    border-bottom: 1px solid #E5E6E8;

    .topshuomain {
      width: 100%;
      margin: 0 auto;
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: bold;
      font-size: 20px;
      color: #000000;
      height: 60px;
      line-height: 60px;
    }
  }
}

.wechat-editor {
  // max-width: 800px;
  width: 100%;
  /* 改为100%适应父容器 */
  max-width: 1200px;
  /* 可选：添加最大宽度 */
  margin: 0 auto;
  /* 保持居中 */
  margin-top: 20px;
  background: #fff;
  // box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding-bottom: 200px;

  .bottomedit {
    height: 77px;
    width: calc(100vw - 210px);
    // border-top: 1px solid #E5E5E5;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    position: fixed;
    bottom: 0;
    background-color: #fff;
    z-index: 999;
    left: 210px;
    right: 0;
    /* 添加内边距 */
    box-sizing: border-box;
    /* 防止溢出 */

    .bottomeditmain {
      width: 95%;
      max-width: 1130px;

      margin: 0 auto;

      display: flex;
      justify-content: space-between;

      .bottomeditmainl {
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 16px;
        color: #CCCCCC;
        line-height: 77px
      }

      .bottomeditmainr {
        // width: 230px;
        display: flex;
        margin-top: 20px;
        justify-content: space-between;

        .subcaogao {
          width: 100px;
          height: 37px;
          background: #4DC0D9;
          border-radius: 4px 4px 4px 4px;
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 16px;
          color: #FFFFFF;
          text-align: center;
          line-height: 37px;
          cursor: pointer;
          margin: 0 20px;
        }

        .subcun {
          width: 100px;
          height: 37px;
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #E5E5E5;
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 16px;
          color: #999999;
          text-align: center;
          line-height: 37px;
          cursor: pointer;

        }
      }
    }
  }


  .editor-wrapper {
    width: 95%;
    margin: 0 auto;
    border: 1px solid #e7e7e7;
    border-radius: 4px;
    overflow: hidden;
    padding-bottom: 100px;

  }

  .editor-toolbar {
    border-bottom: 1px solid #e7e7e7;
    background: #f9f9f9;
    padding: 8px 16px;
  }

  .editor-content {
    padding: 0 16px;
  }

  .editor-title {
    width: 100%;
    border: none;
    outline: none;
    font-size: 24px;
    font-weight: 500;
    line-height: 1.5;
    padding: 20px 0 15px;
    margin: 0;
    color: #222;
    border-bottom: 1px solid #f0f0f0;
    transition: border-color 0.3s;
    text-align: center;

    &:focus {
      // border-bottom-color: #000;
    }

    &::placeholder {
      color: #999;
      font-weight: normal;
    }
  }

  ::v-deep .w-e-bar {
    position: sticky;
    top: 0;
    z-index: 100;
    background: #fff !important;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 8px 16px;
    margin-bottom: 8px;
  }

  /* 调整编辑器内容区域 */
  .editor-body {
    min-height: 500px;
    padding: 16px 0;
    font-size: 16px;
    line-height: 1.8;
    color: #333;
    margin-top: 8px;
    /* 为小工具栏留出空间 */
  }

  // /* 覆盖wangEditor默认样式 */
  // ::v-deep .w-e-text-container {
  //   border: none !important;
  //   box-shadow: none !important;
  // }

  // ::v-deep .w-e-bar {
  //   background: transparent !important;
  //   border-bottom: none !important;
  // }
}
</style>
